using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace Kollektiv.Web.Mvc
{
	public static class System_Reflection_Assembly
	{
		/// <summary>
		/// Searches all types with a controller attribute
        /// for methods with a controller action attribute in an assembly.
		/// </summary>
		/// <param name="assembly">Assembly to search.</param>
		/// <returns>Collection of methods with controller action attributes.</returns>
		public static IEnumerable<MethodInfo> FindControllerActions (this Assembly assembly)
		{
			List<MethodInfo > actions = new List<MethodInfo> ();
			
			foreach (Type t in assembly.GetTypes ()
				.Where(t=>
					!t.IsAbstract &&
					t.GetCustomAttributes(true).Where(a=>a is ControllerAttribute).Any()
				)) {
				foreach (MethodInfo m in t.GetMethods()) {
					if (m.GetCustomAttributes (true).Where (a => a is ControllerActionAttribute).Any ()) {
						actions.Add (m);
					}
				}
			}
			
			return actions.AsReadOnly ();
		}
	}
}

